from StrategyEngine.TradingAlgorithm import TradingAlgorithm
from StrategyEngine.SimulationParameters import SimulationParameters
from StrategyEngine.TradingCalender import GetCalender
from StrategyEngine.TradingEnvironment import TradingEnvironment
# from StrategyEngine.API import order
import StrategyEngine

import Core.Gadget as Gadget
import datetime
import random


from Core.Config import *
config = Config()
database = config.DataBase()
realtime = config.RealTime(db=0)

# Define algorithm
def Initialize(api, context):
    print("initialization")
    #api.PlaceOrder("000001.SZ", 50000)
    pass


def HandledData(api, context, data, dt):
    # print("Handled Data " + str(dt))
    pass


def OnDaily(api, context, dt):
    # print("On Daily " + str(dt))
    pass


def OnWeekly(api, context, dt):
    print(" On Weekly " + str(dt))
    pass


def OnMonthly(api, context, dt):
    print("  --On Monthly-- " + str(dt))
    # ---查询组合---
    portfolio = api.Portfolio()
    # print("Value")
    # print(portfolio.Value)

    # ---查询持仓---
    position = api.Position("000001.SZ")
    if position != None:
        print(position["Equity"])

    # ---调仓列表---
    symbols = []

    # ---手工指定股票---
    symbols.append({"Symbol": "000001.SZ"})
    symbols.append({"Symbol": "000003.SZ"})

    # ---随机选择100只股票进行交易---
    #instruments = context["Instruments"]
    #for i in range(100):
    #    radNum = random.randint(0, len(instruments) - 1)
    #    instrument = instruments[radNum]
    #    symbol = instrument["Symbol"]
    #    symbols.append({"Symbol": symbol})

    api.Rebalance(symbols)
    pass


def OnMonthlyBegin(api, context, dt):
    print("  ++On Monthly Begin++ " + str(dt))
    pass


# ---交易日历---
tradingCalender = GetCalender("SH")

#
datetime1 = datetime.datetime(2015, 1, 1)
datetime2 = datetime.datetime(2016, 1, 3)

# ---回测参数设置---
simulatorParameters = SimulationParameters(datetime1=datetime1,
                                           datetime2=datetime2,
                                           trading_calendar=tradingCalender,
                                           data_frequency="monthly")
# ---交易环境：市场数据，业绩基准---
tradingEnvironment = TradingEnvironment(benchmark_symbol="000300.SH",
                                        database=database,
                                        realtimeView=realtime,
                                        trading_calendar=tradingCalender)

# ---构建策略---
strategy = TradingAlgorithm(name="TestStrategy",
                            initialize=Initialize,
                            handle_data=HandledData,
                            on_daily=OnDaily,
                            on_weekly=OnWeekly,
                            on_monthly=OnMonthly,
                            on_monthly_begin=OnMonthlyBegin,
                            analyze=StrategyEngine.Analyze,
                            simulator_parameters=simulatorParameters,
                            trading_environment=tradingEnvironment)

# ---策略中需要用到的参数---
context = {}


instruments = Gadget.FindListedInstrument(database, datetime1, datetime2)
context["Instruments"] = instruments

# ---开始回测---
statistics = strategy.Run(context=context)


# ---Print Statistics of Strategy---
# statistics.to_csv('myoutput.csv')


